//
//  MCCustomSpecificationsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/4/26.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCCustomSpecificationsViewController: MCViewController {

    
    public var goodsModel = MCGoodsManageHeadModel()
    public var specModel = MCGoodsManageModel()
    public var productIdList = NSArray()
    
    private var billModel = MCCustomSpecifications_billModel()   // 选中的发票Model
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    // MARK: - Custom Delegate
    @objc func rightItemClicked() {

        if goodsModel.type.intValue == 1 { // 自营
            saveEvent_proprietary()
        } else {
            if MCUserinfo_getIsBill() == "0" { // 不开票
                saveEvent_plaformNoTax()
            } else {  // 开票
                saveEvent_platformTax()
            }
        }
    }
    
    @objc func reduceButtonClicked() {
        var goodsCount = Int(inventoryView.textField.text!) ?? 0
 
        goodsCount -= 1
        if goodsCount <= 0 {
            goodsCount = 0
        }
        inventoryView.textField.text = String(goodsCount)
    }
    
    @objc func addButtonClicked() {
        var goodsCount = Int(inventoryView.textField.text!) ?? 0
        goodsCount += 1
        inventoryView.textField.text = String(goodsCount)
    }
    
    @objc func showInMarketViewEvent() {
        showInMarketView.selectedButton.isSelected = !showInMarketView.selectedButton.isSelected
    }
    
    @objc func giveThirdViewEvent() {
        giveThirdView.selectedButton.isSelected = !giveThirdView.selectedButton.isSelected

    }
    
    @objc func taxTypeViewEvent() {
        
        let arrayM = NSMutableArray()
        for model in billArrayM {
            arrayM.add((model as! MCCustomSpecifications_billModel).billMessage)
        }
        createPicerView(type: 0, array: arrayM)
    }
    
    
    // MARK: - Action
    
    // MARK: - Network
    func sendNetworking() {
        
        goodsDetailView.model = goodsModel
        goodsDetailView.countLabel.text = "已选:" + String(productIdList.count) + "种货品"
        inventoryView.textField.text = String(specModel.inventoryNum)
        saleView.textField.text = String.init(format: "%.2f", CGFloat(specModel.salePrice)/100)
        
        proportionView.textField.text = goodsModel.goodsCommission.stringValue
        proportionView.promptLabel.text = "最低比例" + specModel.platformRate.stringValue + "%"
        noTaxPriceView.textField.text = String.init(format: "%.2f", CGFloat(specModel.settlementPrice)/100)
            
        giveThirdView.selectedButton.isSelected = specModel.isCooperate.boolValue
        showInMarketView.selectedButton.isSelected = specModel.status.boolValue
        
        
        if !specModel.billMessage.isEmpty {
            taxTypeView.contentButton.setTitle(specModel.billMessage, for: UIControlState.normal)
            taxTypeView.contentButton.isSelected = true
            billModel.billCode = specModel.billCode
            billModel.billMessage = specModel.billMessage
        }
        

        sendNetworking_findBillTypeList()
    }
    
    
    func sendNetworking_findBillTypeList() {
        let para = [:] as [String : Any]
        
        MCNetwork_post(url: JAVA_findBillTypeList, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataArray = response["data"] as? NSArray ?? []
            
            for dict in dataArray {
                let model = MCCustomSpecifications_billModel()
                model.setValuesForKeys(dict as! [String : Any])
                self.billArrayM.add(model)
            }
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    func createPicerView(type:Int,array:NSArray) {
        let pickerView = MCSinglePickerView()
        pickerView.delegate = self
        pickerView.dataArray = array
        pickerView.type = type
        view.window!.addSubview(pickerView)
        pickerView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "规格定制"
        self.view.backgroundColor = UIColor.white
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("保存", target: self, selector: #selector(rightItemClicked))
    }
    
    func initUI() {
        view.addSubview(goodsDetailView)
        goodsDetailView.snp.remakeConstraints { (make) ->Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(100)
        }
        
        view.addSubview(inventoryView)
        inventoryView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(goodsDetailView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(saleView)
        saleView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(inventoryView.snp.bottom)
            make.height.equalTo(50)
        }

        if goodsModel.type.intValue == 1 {  // 自营
            initUI_proprietaryOrder()
        } else {  // 平台
            
            view.addSubview(proportionView)
            proportionView.snp.remakeConstraints { (make) ->Void in
                make.left.equalTo(10)
                make.right.equalTo(-10)
                make.top.equalTo(saleView.snp.bottom)
                make.height.equalTo(50)
            }

            if MCUserinfo_getIsBill() == "0" {  // 0不开票
                initUI_platformNoTaxOrder()
                noTaxPriceView.textField.isEnabled = false
            } else {  // 开票
                initUI_platformTaxOrder()
                noTaxPriceView.textField.isEnabled = true
                taxPriceView.textField.isEnabled = false

                noTaxPriceView.promptLabel.text = "不可低于含税价"
            }
        }
    }
    
    // 自营订单的UI
    func initUI_proprietaryOrder() {
        view.addSubview(showInMarketView)
        showInMarketView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(saleView.snp.bottom)
            make.height.equalTo(50)
        }
    }
    
    // 平台不含税订单的UI
    func initUI_platformNoTaxOrder() {
        view.addSubview(noTaxPriceView)
        noTaxPriceView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(proportionView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(giveThirdView)
        giveThirdView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(noTaxPriceView.snp.bottom)
            make.height.equalTo(50)
        }

        view.addSubview(showInMarketView)
        showInMarketView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(giveThirdView.snp.bottom)
            make.height.equalTo(50)
        }
    }

    
    // 平台含税订单的UI
    func initUI_platformTaxOrder() {
        view.addSubview(taxPriceView)
        taxPriceView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(proportionView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(noTaxPriceView)
        noTaxPriceView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(taxPriceView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(taxTypeView)
        taxTypeView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(noTaxPriceView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(giveThirdView)
        giveThirdView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(taxTypeView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(showInMarketView)
        showInMarketView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(giveThirdView.snp.bottom)
            make.height.equalTo(50)
        }
    }
    
    func saveEvent_proprietary() {
        sendNetworking_save(type: 0)
    }
    
    func saveEvent_plaformNoTax() {
        
        sendNetworking_save(type: 1)
    }
    
    func saveEvent_platformTax() {
        
        sendNetworking_save(type: 2)
    }
    
    func sendNetworking_save(type:Int) {

        var status = 0
        if showInMarketView.selectedButton.isSelected {
            status = 1
        } else {
            status = 0
        }
        
        var isCooperate = 0
        if giveThirdView.selectedButton.isSelected {
            isCooperate = 1
        } else {
            isCooperate = 0
        }
        
        
        
        
        
        let proportion = Double(proportionView.textField.text ?? "0")!
        let sale = Double(saleView.textField.text ?? "0")! * 100
        var taxSettlementPrice = (1 - proportion/100) * sale
        let noTaxSettlementPrice = Double(noTaxPriceView.textField.text!)!*100
        
        
        if type == 2 {
            if billModel.billCode == 0 || billModel.billMessage.isEmpty {
                MCHUD_text(message: "请选择开票类型", view: self.view, delay: 1.2)
                return
            }
        }

        // 平台商品才有的校验
        if type > 0 {
            // 两个限制
            // (1 - 平台佣金比例) * 实际售价 = 含税结算价
            // 最低佣金比例
            if specModel.platformRate.doubleValue > proportion {
                MCHUD_text(message: "佣金比例 不可低于 平台最低佣金", view: self.view, delay: 1.2)
                return
            }
            
            if taxSettlementPrice < noTaxSettlementPrice {
                MCAlterController_oneOptions(vc: self, message: "不含税结算价不可高于\n (1 - 佣金比例) * 实际售价", cancle: nil)
                return
            }
        }

        
        if type != 2 {
            taxSettlementPrice = 0
        }
        
        

        
        let para = [
            "goodsId"         : goodsModel.goodsId.intValue,
            "productIdList"   : productIdList,
            "storeId"         :MCUserinfo_getStoreId(),
            "isStockWarn"     : 0,
            "storeUserId"     : MCUserinfo_getUserId(),
            
            "status"          : status,
            "inventoryNum"    : inventoryView.textField.text ?? "0",
            "salePrice"       : Double(saleView.textField.text!)!*100,
            
            "profitRate"      : proportion,
            "settlementPrice" : noTaxSettlementPrice,
            "isCooperate"     : isCooperate,

            "taxSettlementPrice" : taxSettlementPrice,
            "billType"           : billModel.billCode
            
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_editStoreProductInfo, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            MCHUD_text(message: "设置成功", view: self.view, delay: 1.5)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                self.navigationController?.popViewController(animated: true)
            })
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    // MARK: - Setter & Getter
    lazy var billArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    
    // 商品模块
    private lazy var goodsDetailView: MCCustomSpecificationsGoodsView = {
        let view = MCCustomSpecificationsGoodsView()
        view.backgroundColor = UIColor.yellow
        return view
    }()
    
    // 库存模块
    private lazy var inventoryView: MCGoodsManageSetting_countView = {
        let view = MCGoodsManageSetting_countView()
        view.titleLabel.text = "库存(个)"
        view.textField.text = "1"
//        view.textField.becomeFirstResponder()
        view.textField.keyboardType = UIKeyboardType.numberPad
        view.reduceButton.addTarget(self, action: #selector(reduceButtonClicked), for: UIControlEvents.touchUpInside)
        view.addButton.addTarget(self, action: #selector(addButtonClicked), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    // 店铺售价模块
    private lazy var saleView: MCGoodsManageSetting_priceView = {
        let view = MCGoodsManageSetting_priceView()
        view.titleLabel.text = "实际售价(¥)"
        view.textField.text = "0.01"
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.textField.delegate = self
        return view
    }()
    
    // 佣金比例模块
    private lazy var proportionView: MCGoodsManageSetting_priceView = {
        let view = MCGoodsManageSetting_priceView()
        view.titleLabel.text = "佣金比例(%)"
        view.textField.text = "10"
        view.textField.keyboardType = UIKeyboardType.numberPad
        view.textField.delegate = self
        return view
    }()
    
    private lazy var noTaxPriceView: MCGoodsManageSetting_priceView = {
        let view = MCGoodsManageSetting_priceView()
        view.titleLabel.text = "不含税结算价(¥)"
        view.textField.text = "0.01"
        view.textField.keyboardType = UIKeyboardType.decimalPad
        view.textField.delegate = self
        return view
    }()

    private lazy var taxPriceView: MCGoodsManageSetting_priceView = {
        let view = MCGoodsManageSetting_priceView()
        view.titleLabel.text = "含税结算价(¥)"
        view.textField.text = "0.01"
        view.textField.keyboardType = UIKeyboardType.decimalPad
        //        view.textField.delegate = self
        return view
    }()

    lazy var taxTypeView: MCAddTicketEventView = {
        let view = MCAddTicketEventView()
        view.titleLabel.text = "开票类型"
        view.contentButton.setTitle("请选择开票类型", for: UIControlState.normal)
        view.contentButton.addTarget(self, action: #selector(taxTypeViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()

    

    
    // 是否给第三方
    lazy var giveThirdView: MCAfterSaleDetailFooter_selectedView = {
        let view = MCAfterSaleDetailFooter_selectedView()
        view.nameLabel.text = "是否推荐给第三方销售"
        view.selectedButton.isSelected = true
        view.selectedButton.addTarget(self, action: #selector(giveThirdViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()

    
    // 微商城中是否显示
    lazy var showInMarketView: MCAfterSaleDetailFooter_selectedView = {
        let view = MCAfterSaleDetailFooter_selectedView()
        view.nameLabel.text = "微商城中是否显示"
        view.selectedButton.isSelected = true
        view.selectedButton.addTarget(self, action: #selector(showInMarketViewEvent), for: UIControlEvents.touchUpInside)
        return view
    }()
}


extension MCCustomSpecificationsViewController : UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
     
        let salePrice = saleView.textField.text ?? "0"
        let proportion = proportionView.textField.text ?? "0"
        let price = Double(salePrice)! * (1 - Double(proportion)! / 100.0)
        
        if MCUserinfo_getIsBill() == "0" {  // 0不开票
            noTaxPriceView.textField.text = String.init(format: "%.2f", price)
        } else {  // 开票
            taxPriceView.textField.text = String.init(format: "%.2f", price)
        }
    }
}


extension MCCustomSpecificationsViewController : MCSinglePickerViewDelegate {
    
    func MCSinglePickerViewSelectedRow(type: Int, row: Int, str: String) {
        self.billModel = self.billArrayM[row] as! MCCustomSpecifications_billModel

        taxTypeView.contentButton.setTitle(billModel.billMessage, for: UIControlState.normal)
        taxTypeView.contentButton.isSelected = true
    }
}







class MCGoodsManageSetting_countView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(titleLabel)
        titleLabel.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.left.equalTo(self)
        }
        
        
        self.addSubview(addButton)
        addButton.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.right.equalTo(self)
        }
        
        self.addSubview(textField)
        textField.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.right.equalTo(addButton.snp.left).offset(-5)
            make.size.equalTo(CGSize.init(width: 64, height: 30))
        }
        
        self.addSubview(reduceButton)
        reduceButton.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.right.equalTo(textField.snp.left).offset(-5)
        }
        
        self.addSubview(lineView)
        lineView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(1)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public lazy var titleLabel: UILabel = {
        let label = UILabel.init()
        label.font = MCFont(14)
        label.textColor = UIColor.MCBlack
        return label
    }()
    
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = UIColor.MCGray_light
        textField.font = MCFont(14)
        textField.textAlignment = NSTextAlignment.center
        return textField
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }()
    
    public lazy var reduceButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "GoodsManage_reduce"), for: UIControlState.normal)
        return button
    }()
    
    
    public lazy var addButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "GoodsManage_add"), for: UIControlState.normal)
        return button
    }()
    
}


class MCGoodsManageSetting_priceView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(titleLabel)
        titleLabel.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.left.equalTo(self)
        }
        
        self.addSubview(promptLabel)
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.bottom.equalTo(titleLabel).offset(1)
            make.left.equalTo(titleLabel.snp.right).offset(3)
        }
        
        self.addSubview(textField)
        textField.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.right.equalTo(self)
            make.size.equalTo(CGSize.init(width: 120, height: 30))
        }
        
        self.addSubview(lineView)
        lineView.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(1)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    public lazy var titleLabel: UILabel = {
        let label = UILabel.init()
        label.font = MCFont(14)
        label.textColor = UIColor.MCBlack
        return label
    }()
    
    public lazy var promptLabel: UILabel = {
        let label = UILabel.init()
        label.font = MCFont(11)
        label.textColor = UIColor.MCGray_middle
        return label
    }()
    
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = UIColor.MCGray_light
        textField.font = MCFont(14)
        textField.textAlignment = NSTextAlignment.center
        return textField
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.MCGray_light
        return view
    }()
}
